package com.zhike.common.utils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import org.springframework.stereotype.Component;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class SmsUtil {

    public AsyncClient buildClient(String accessKeyId, String accessKeySecret) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                // .securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS
                // token
                .build());

        return AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                // .setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
    }

    public SendSmsRequest buildRequest(String phoneNumbers, String signName, String templateCode,
            String templateParam) {
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumbers)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam(templateParam)
                .build();
        return sendSmsRequest;
    }

    public String send(AsyncClient client,SendSmsRequest request) throws ExecutionException, InterruptedException {

        try {
            SendSmsResponse resp = null;
            CompletableFuture<SendSmsResponse> response = client.sendSms(request);
            resp = response.get();
            log.info("验证码请求成功: {}", resp);
            return new Gson().toJson(resp);
        } finally {
            client.close();
        }
    }

}
